from django.shortcuts import render,HttpResponse
from .form import MessageBoardForm, RegisterForm, ArticleForm
# 请求验证装饰器 只允许 POST方法 和 GET 方法的请求
from django.views.decorators.http import require_http_methods


# Create your views here.
## index
@require_http_methods(['GET','POST'])
def index(request):
    print("这里是首页。。。。")
    ## 判断是 GET请求 还是 POST请求
    if request.method == "GET":
        form = MessageBoardForm()
        return render(request,'index.html',{'form':form})  ## GET 方法直接 返回 index.html
    else:
        form = MessageBoardForm(request.POST)
        ## 验证表单 是否符合 model 中的要求
        if form.is_valid():
            title   =   form.cleaned_data.get('title')
            content =   form.cleaned_data.get('content')
            email   =   form.cleaned_data.get('email')
            return HttpResponse(f"标题是：{title},内容是：{content},邮件是：{email}")
        else:
            print(form.errors.get_json_data())
            return HttpResponse(f"表单验证失败,{form.errors}")

## 注册手机号模型
@require_http_methods(['GET','POST'])
def telephoneview(request):
        ## GET
    if request.method == "GET":
        info = RegisterForm()
        return render(request,'register.html')
    else:
        info = RegisterForm(request.POST)
        ## 验证提交的信息
        if info.is_valid():
            tele = info.cleaned_data.get("telephone")
            return HttpResponse(f"手机号是：{tele}")
        else:
            print(info.errors.get_json_data())   ## get_json_data() 去除 html 标签
            return HttpResponse(f"表单验证失败：{info.errors}")

## ModelForm
@require_http_methods(['GET','POST'])
def modelview(request):
    if request.method == "GET":
        form = ArticleForm()
        return render(request,'articleForm.html')
    else:
        form = ArticleForm(request.POST)
        ## 验证表单信息
        if form.is_valid():
            title = form.cleaned_data.get('title')
            content = form.cleaned_data.get('content')
            return HttpResponse(f"标题是：{title},内容是：{content}")
        else:
            result = form.errors.get_json_data()
            print(result)
            return HttpResponse(f"表单验证失败：{result}")




